package site.ycsyxt.framework.service.impl;

import site.ycsyxt.framework.manager.AsyncManager;
import site.ycsyxt.framework.service.MailService;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import java.util.TimerTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 * @author ycs(15241496739 @ 163.com)
 * @date 2021/11/21
 **/
@Service
public class MailServiceImpl implements MailService {

    /**
     * 发送邮箱地址
     */
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 是否开启邮件发送功能
     */
    @Value("${spring.mail.enabled}")
    private boolean enabled;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void send(String to, String subject, String content) {
        if (!enabled) {
            return;
        }
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                mailSender.send(message);
            }
        });
    }
}
